﻿using System;

namespace SnippetBox.Core.Common.Extensions {
    public static class DateTimeExtensions {
        /// <summary>
        /// Converts the specified DateTime to its relative date.
        /// http://tiredblogger.wordpress.com/2008/08/21/creating-twitter-esque-relative-dates-in-c/
        /// </summary>
        /// <param name="dateTime">The DateTime to convert.</param>
        /// <param name="prefix">The prefix of the resulting string</param>
        /// <param name="suffix">The suffix of the resulting string</param>
        /// <returns>A string value based on the relative date
        /// of the datetime as compared to the current date.</returns>
        public static string ToRelativeDate(this DateTime dateTime, string prefix = "about ", string suffix = " ago") {
            var timeSpan = DateTime.Now - dateTime;

            // span is less than or equal to 60 seconds, measure in seconds.
            if (timeSpan <= TimeSpan.FromSeconds(60)) {
                return timeSpan.Seconds + " seconds" + suffix;
            }
            // span is less than or equal to 60 minutes, measure in minutes.
            if (timeSpan <= TimeSpan.FromMinutes(60)) {
                return timeSpan.Minutes > 1
                    ? prefix + timeSpan.Minutes + " minutes" + suffix
                    : prefix + "a minute" + suffix;
            }
            // span is less than or equal to 24 hours, measure in hours.
            if (timeSpan <= TimeSpan.FromHours(24)) {
                return timeSpan.Hours > 1
                    ? prefix + timeSpan.Hours + " hours" + suffix
                    : prefix + "an hour" + suffix;
            }
            // span is less than or equal to 30 days (1 month), measure in days.
            if (timeSpan <= TimeSpan.FromDays(30)) {
                return timeSpan.Days > 1
                    ? prefix + timeSpan.Days + " days" + suffix
                    : prefix + "a day" + suffix;
            }
            // span is less than or equal to 365 days (1 year), measure in months.
            if (timeSpan <= TimeSpan.FromDays(365)) {
                return timeSpan.Days > 30
                    ? prefix + timeSpan.Days / 30 + " months" + suffix
                    : prefix + "a month" + suffix;
            }

            // span is greater than 365 days (1 year), measure in years.
            return timeSpan.Days > 365
                ? prefix + timeSpan.Days / 365 + " years" + suffix
                : prefix + "a year" + suffix;
        }
    }
}